package io.github.aaron.commonadmin.base.util;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * @Author: AaronF
 * @Date: 2025/08/25/22:48
 * @Description: 分页工具类
 * 该类方法入参页码从1开始
 */
public class PageUtils {

    /**
     * 默认按照id降序
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public static Pageable of(Integer pageNumber, Integer pageSize){
        return of(pageNumber,pageSize, Sort.Direction.DESC,"id");
    }

    /**
     * 构造分页参数
     * @param pageNumber 页码从1开始
     * @param pageSize
     * @param direction
     * @param properties
     * @return 页码从0开始
     */
    public static Pageable of(Integer pageNumber, Integer pageSize, Sort.Direction direction, String... properties){
        int correctPageNumber = correctPageNumber(pageNumber);
        int correctPageSize = correctPageSize(pageSize);
        return PageRequest.of(correctPageNumber,correctPageSize,direction,properties);
    }

    /**
     * 修正页码，改为从0开始
     * @param pageable
     * @return
     */
    public static Pageable correct(Pageable pageable){
        int correctPageNumber = correctPageNumber(pageable.getPageNumber());
        return pageable.withPage(correctPageNumber);
    }

    private static int correctPageSize(Integer pageSize) {
        return pageSize == null || pageSize <= 0 ? 10 : pageSize;
    }

    private static int correctPageNumber(Integer pageNumber) {
        return pageNumber == null || pageNumber <= 0 ? 0 : pageNumber - 1;
    }


}
